package concurrency;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mr.Sun
 * @date 2022年09月04日 11:20
 *
 * 演示使用Lock对象尝试获取锁
 */
public class AttemptLocking {
    private ReentrantLock lock = new ReentrantLock();
    public void unTimed () {
        boolean captured = lock.tryLock();
        try {
            System.out.println("tryLock(): " + captured);
        } finally {
            // 获取到锁才能执行释放锁操作，否则会出现IllegalMonitorStateException异常
            if (captured) {
                lock.unlock();
            }
        }
    }

    public void timed () {
        boolean captured = false;
        try {
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try {
            System.out.println("lock.tryLock(2, TimeUnit.MINUTES): " + captured);
        } finally {
            if (captured) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final AttemptLocking al = new AttemptLocking();
        al.unTimed(); // True -- 锁是可用的
        al.timed(); // True -- 锁是可用的

        // 现在创建一个单独的任务来获取锁
        new Thread() {
            {setDaemon(true);}

            @Override
            public void run() {
                al.lock.lock();
                System.out.println("acquired");
            }
        }.start();
        // 给第二个任务一个机会
        Thread.sleep(100);
        al.unTimed(); // false -- lock grabbed by task
        al.timed(); // false -- lock grabbed by task
    }

} /* Output:
tryLock(): true
lock.tryLock(2, TimeUnit.MINUTES): true
acquired
tryLock(): false
lock.tryLock(2, TimeUnit.MINUTES): false
*///:~
